

package com.codegen.gbcodegen.controller;

import cn.hutool.core.io.IoUtil;
import com.codegen.gbcodegen.entity.GenConfig;
import com.codegen.gbcodegen.service.SysGeneratorService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;

/**
 * 代码生成器
 */
@RestController
@AllArgsConstructor
@RequestMapping("/generator")
public class SysGeneratorController {

    private final SysGeneratorService sysGeneratorService;


    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
    /**
     * 生成代码
     */
    @SneakyThrows
    @RequestMapping(value = "/code", method = RequestMethod.POST)
    public void generatorCode(@RequestParam("packageName") String packageName,
                              @RequestParam("tableName") String tableName,
                              @RequestParam("author") String author,
                              @RequestParam("moduleName") String moduleName,
                              @RequestParam("tablePrefix") String tablePrefix,
                              @RequestParam("comments") String comments,HttpServletResponse response) {
        GenConfig genConfig = new GenConfig();
        genConfig.setAuthor(author);//作者
        genConfig.setComments(comments);//注释
        genConfig.setModuleName(moduleName);//模块
        genConfig.setPackageName(packageName);//包名
        genConfig.setTableName(tableName);//表名
        genConfig.setTablePrefix(tablePrefix);//前缀
        byte[] data = sysGeneratorService.generatorCode(genConfig);
        sendMsg(tableName);
        //下载
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }




    @SneakyThrows
    @RequestMapping(value = "/test1", method = RequestMethod.POST)
    public String generatorCode(){


        return "test";
    }


    private void  sendMsg(String tableName){
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", tableName);
    }

}
